package cn.ybz21.hibot.monitor;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.AppMonitor;
import cn.ybz21.hibot.bean.Node;
import cn.ybz21.hibot.db.service.AppDAO;
import cn.ybz21.hibot.net.NetCenter;
import cn.ybz21.hibot.util.StaticValues;

import com.google.gson.Gson;

public class AppWatcher extends Thread {
	AppDAO appService;

	public static void main(String[] args) {
		new AppWatcher().start();
	}

	@Override
	public void run() {
		while (true) {
			startMonitor();
			try {
				Thread.sleep(20000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public AppWatcher() {
		init();
	}

	private void init() {
		appService = new AppDAO();
	}

	public void startMonitor() {
		System.out.println("------------------------");
		System.out.println("start query nodes on ros");
		List<Node> realNodes = new NodeInfoCollect().getInfo();
		System.out.println("end query nodes on ros\n");
		System.out.println("start get App Info");
		List<App> apps = queryRunApps();
		int i = 0;
		for (App app : apps) {
			i++;
			List<Node> appNodes = app.nodes;
			boolean healthFlag = true;
			for (Node appNode : appNodes) {
				boolean nodeFlag = false;
				for (Node realNode : realNodes) {
					if (realNode.name.equals(appNode.name)) {
						nodeFlag = true;
						appNode.cpu = realNode.cpu;
						appNode.memory = realNode.memory;
						appNode.pid = realNode.pid;
						break;
					}
				}
				if (!nodeFlag) {
					// 节点不正常
					healthFlag = false;
				}
			}

			if (!healthFlag) {
				// 应用程序不健康
				System.err.println("APP " + app.name + " is NOT HEALTH!!!");
				app.health = false;
				// TODO 重启应用
			} else {
				app.health = true;
			}
			double sumCpu = 0;
			double sumMemory = 0;
			for (Node appNode : appNodes) {
				sumCpu += appNode.cpu;
				sumMemory += appNode.memory;
			}
			app.cpu = sumCpu;
			app.memory = sumMemory;
			System.out.println("\r\t" + i + " " + app);
		}
		System.out.println("end get App Info\n");
		System.out.println("start upload App Info");
		uploadAppInfo(apps);
		System.out.println("end upload App Info");
		System.out.println("------------------------\n");
	}

	private void uploadAppInfo(List<App> apps) {
		Gson gson = new Gson();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		AppMonitor appMonitor = new AppMonitor();
		appMonitor.apps = apps;
		appMonitor.clientId = StaticValues.ID_CLIENT;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		appMonitor.date = formatter.format(new Date());

		params.add(new BasicNameValuePair("data", gson.toJson(appMonitor)));

		new NetCenter().httpPost(StaticValues.URL_UPLOAD_APP_INFO, params);
	}

	public List<App> queryRunApps() {
		return appService.queryRuningApp();
	}
}
